package com.have.to.base;



import com.have.to.vm.BaseVM;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

class BaseUIHelper<VM extends BaseVM> {

    private BaseUI<VM> baseUI;

    public void init(BaseUI<VM> ui) {
        this.baseUI = ui;
        if (!(this.baseUI instanceof AppVmActivity) && !(baseUI instanceof AppVmFragment)) {
            throw new IllegalStateException("baseUI must be a instances of BaseActivity or BaseFragment");
        }
        //初始化当前的ViewModel
        initCurrentVM();
        //初始化自定义的ViewModel列表
        initBaseVMs();
    }

    //region ViewModel code
    private VM getViewModel(Class<VM> cls) {
        return baseUI.getVM(cls);
    }

    /**
     * 默认当前UI只有一个VM的情况，通过范型默认初始化
     */
    private void initCurrentVM() {
        //这里获得到的是类的泛型的类型
//        Type genericSuperclass = getClass().getGenericSuperclass();
        Type genericSuperclass = baseUI.getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
//            ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
            ParameterizedType type = (ParameterizedType) baseUI.getClass().getGenericSuperclass();
            Type[] actualTypeArguments = type.getActualTypeArguments();
            Type actualTypeArgument = actualTypeArguments[0];
            if (actualTypeArgument != null) {
                Class<VM> tClass = (Class<VM>) actualTypeArgument;
                VM mCurrentVM = getViewModel(tClass);
                initBaseVM(mCurrentVM);
                baseUI.setCurrentVM(mCurrentVM);
            }
        } else {
        }
    }

    private void initBaseVM(BaseVM baseVM) {
    }

    /**
     * 可选的，初始化多个ViewModel的统一入口
     *
     */
    private List<BaseVM> initVMList() {
        return baseUI.initVMList();
    }

    /**
     * @see AppVmActivity#initVMList()
     * 初始化多个ViewModel 需要继承自BaseVM
     */
    private void initBaseVMs() {
        List<BaseVM> baseVMS = initVMList();
        if (baseVMS != null && baseVMS.size() > 0) {
            for (BaseVM t : baseVMS) {
                initBaseVM(t);
            }
        }
    }
}
